<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用户列表卡片区 -->
    <el-card>
      <!--   用户查询表单   -->
      <el-form :inline="true" :model="formInline">
        <el-form-item label="部门" label-width="70px">
          <el-select clearable v-model="formInline.departmentId" placeholder="请选择部门">
            <el-option
                v-for="item in cities"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.departmentCount }}人</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" label-width="70px">
          <el-input clearable v-model="formInline.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="70px">
          <el-input clearable v-model="formInline.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="性别" label-width="70px">
          <el-radio-group v-model="formInline.sex">
            <el-radio label="">全部</el-radio>
            <el-radio label="0">帅哥</el-radio>
            <el-radio label="1">美女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="昵称" label-width="70px">
          <el-input clearable v-model="formInline.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item style="margin-left:50px;">
          <el-button @click="onRefresh" icon="el-icon-refresh" type="warning">重置</el-button>
          <el-button @click="onSubmit" icon="el-icon-search" type="primary">查询</el-button>
          <el-button @click="addDialogVisible=true" icon="el-icon-plus" type="success">添加</el-button>
          <el-button @click="onExportExcel" icon="el-icon-download" type="info">导出</el-button>
        </el-form-item>
      </el-form>
      <!--表格-->
      <el-table
          :data="tableData"
          border
          size="small"
          style="width: 100%;height: 100%">
        <el-table-column
            align="center"
            prop="id"
            label="#"
            min-width
            width="50">
        </el-table-column>
        <el-table-column
            align="center"
            prop="username"
            label="用户名"
            width="140">
        </el-table-column>
        <el-table-column
            align="center"
            prop="sex"
            label="性别"
            width="80">
          <template slot-scope="scope">
            <el-tag size="small" type="success" v-if="scope.row.sex===0">帅哥</el-tag>
            <el-tag size="small" type="warning" v-else-if="scope.row.sex === 1">美女</el-tag>
            <el-tag size="small" type="error" v-else>未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            prop="departmentName"
            label="所属部门"
            width="180">
        </el-table-column>
        <el-table-column
            align="center"
            prop="birth"
            label="生日"
            width="180">
        </el-table-column>
        <el-table-column
            align="center"
            prop="email"
            label="邮箱"
            width="180">
        </el-table-column>
        <el-table-column
            align="center"
            prop="phoneNumber"
            label="电话"
            width="180">
        </el-table-column>
        <el-table-column
            align="center"
            label="是否禁用"
            width="120">
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.status === 1"
                active-color="#13ce66"
                inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            label="操作">
          <template slot-scope="scope">
            <el-button @click="showUpdateDialog(scope.row)" class="el-icon-edit" type="primary"></el-button>
            <el-button @click='onDelete(scope.row.id)' class="el-icon-delete" type="danger"></el-button>
            <el-button @click="" class="el-icon-setting" type="success"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--   分页   -->
      <el-pagination
          :align="'end'"
          style="margin-top:10px;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.current"
          :page-sizes="[5,6,7,8]"
          :page-size="pageInfo.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" @close="addClose" :visible.sync="addDialogVisible" width="50%;">
        <!-- 表单 -->
        <span>
          <el-form
              :model="addForm"
              :rules="addFormRules"
              ref="addFormRef"
              label-width="80px"
          >
            <el-row>
              <el-form-item label="头像">
                <el-upload
                    class="avatar-uploader"
                    action="http://localhost:8081/file/uploadImgFile"
                    :show-file-list="false"
                    :on-success="handleSuccessFile"
                    :on-error="handleErrorFile"
                >
                  <img v-if="addForm.avatar" :src="addForm.avatar" class="avatar" alt="">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <el-button type="primary">添加头像</el-button>
                </el-upload>
              </el-form-item>
            </el-row>
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="部门" prop="departmentId">
                    <el-select v-model="addForm.departmentId" placeholder="请选择所属部门">
                      <el-option
                          v-for="department in cities"
                          :key="department.id"
                          :label="department.name"
                          :value="department.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="addForm.nickname"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="addForm.sex">
                      <el-radio :label="1">帅哥</el-radio>
                      <el-radio :label="0">美女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="phoneNumber">
              <el-input v-model="addForm.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item prop="birth" label="生日">
              <el-col :span="11">
                <el-date-picker
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择出生日期"
                    v-model="addForm.birth"
                    style="width: 100%;"
                ></el-date-picker>
              </el-col>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
              type="primary"
              @click="addUser"
              :loading="btnLoading"
              :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户对话框 -->
      <el-dialog title="修改用户" :visible.sync="updateDialogVisible" width="50%" @close="updateClose">
        <span>
          <el-form
              :model="updateFrom"
              :rules="addFormRules"
              ref="updateFormRef"
              label-width="80px"
          >
            <el-row>
              <el-form-item label="头像">
                <el-upload
                    class="avatar-uploader"
                    action="http://localhost:8081/file/uploadImgFile"
                    :show-file-list="false"
                    :on-success="handleSuccessFile"
                    :on-error="handleErrorFile"
                >
                  <img v-if="updateFrom.avatar" :src="updateFrom.avatar" class="avatar" alt="">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <el-button type="primary">更换头像</el-button>
                </el-upload>
              </el-form-item>
            </el-row>
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="updateFrom.username" :disabled="true"></el-input>
                    <el-input
                        type="hidden"
                        v-model="updateFrom.id"
                        :disabled="true"
                        style="display:none;"
                    ></el-input>
                        </el-form-item>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="grid-content bg-purple-light">
                        <el-form-item label="部门" prop="departmentId">
                          <el-select v-model="updateFrom.departmentId" placeholder="请选择所属部门">
                            <el-option
                                v-for="department in cities"
                                :key="department.id"
                                :label="department.name"
                                :value="department.id"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </div>
                    </el-col>
                  </el-row>
            <el-row>
                    <el-col :span="10">
                      <div class="grid-content bg-purple">
                        <el-form-item label="昵称" prop="nickname">
                          <el-input v-model="updateFrom.nickname"></el-input>
                        </el-form-item>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="grid-content bg-purple-light">
                        <el-form-item label="性别" prop="sex">
                          <el-radio-group v-model="updateFrom.sex">
                            <el-radio :label="0">帅哥</el-radio>
                            <el-radio :label="1">美女</el-radio>
                          </el-radio-group>
                        </el-form-item>
                      </div>
                    </el-col>
                  </el-row>
            <el-form-item label="邮箱" prop="email">
                    <el-input v-model="updateFrom.email"></el-input>
                  </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
                    <el-input v-model="updateFrom.phoneNumber"></el-input>
                  </el-form-item>
            <el-form-item prop="birth" label="生日">
                    <el-col :span="11">
                      <el-date-picker
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择出生日期"
                          v-model="updateFrom.birth"
                          style="width: 100%;"
                      ></el-date-picker>
                    </el-col>
                  </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
                <el-button @click="updateDialogVisible = false">取 消</el-button>
                <el-button
                    type="primary"
                    @click="updateUser"
                    :loading="btnLoading"
                    :disabled="btnDisabled"
                >确 定</el-button>
              </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
import {addUser, deleteAvatar, deleteUser, getAllUsers, loadDepartment, updateUser, exportExcel} from "@/api";

export default {
  name: 'Users',
  data() {
    // 邮箱验证
    let checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的邮箱格式"));
        }
      }, 100);
    };
    // 手机号码验证
    let checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[34578]\d{9}$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        // Number.isInteger是es6验证数字是否为整数的方法,实际输入的数字总是识别成字符串
        // 所以在前面加了一个+实现隐式转换

        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };
    return {
      btnLoading: false, // 启用加载图标
      btnDisabled: false, // 是否禁用按钮
      addDialogVisible: false, //添加对话框,
      updateDialogVisible: false, //修改对话框
      formInline: {
        username: '',
        nickname: '',
        email: '',
        sex: '',
        departmentId: '',
      }, // 查询表单
      cities: [], // 部门选项
      tableData: [
        {
          id: 1,
          username: 'jack',
          sex: 1,
          departmentName: '开发部',
          birth: '2001-09-01',
          email: 'admin@qq.com',
          phoneNumber: '123456789123',
          status: 1
        },
        {
          avatar: "http://thirdqq.qlogo.cn/g?b=oidb&k=icTYjyV5afABvE1v4ge9SLg&s=100&t=1584195695",
          birth: 1585267200000,
          createTime: 1560546736000,
          deleted: false,
          departmentId: 1,
          email: "Jana@126.com",
          id: 5,
          modifiedTime: 1584591640000,
          nickname: "NieChangan",
          password: "ec4c46a53d0f9db5a805006bac5aa912",
          phoneNumber: "17744444444",
          salt: "b546f820-7ca3-4b75-9038-3d4abb5d",
          sex: 1,
          status: 1,
          type: 0,
          username: "xiaoge"
        }
      ], // 表单数据
      pageInfo: {
        current: 1,
        total: 100,
        size: 6
      }, // 分页数据
      addForm: {
        username: "",
        nickname: "",
        avatar: "",
        password: "",
        email: "",
        phoneNumber: "",
        sex: "",
        birth: ""
      }, //添加表单
      updateFrom: {
        username: "",
        nickname: "",
        avatar: "",
        password: "",
        email: "",
        phoneNumber: "",
        sex: "",
        birth: ""
      }, //修改表单
      addFormRules: {
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"},
          {min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur"}
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {min: 3, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur"}
        ],
        departmentId: [
          {required: true, message: "请选择部门", trigger: "blur"}
        ],
        sex: [{required: true, message: "请选择性别", trigger: "blur"}],
        birth: [{required: true, message: "请填写出生日期", trigger: "blur"}],
        email: [{required: true, validator: checkEmail, trigger: "blur"}],
        phoneNumber: [
          {
            required: true,
            message: "请输入联系方式",
            validator: checkPhone,
            trigger: "blur"
          }
        ],
        nickname: [
          {required: true, message: "请输入昵称", trigger: "blur"},
          {min: 5, max: 10, message: "长度在 5 到 10 个字符", trigger: "blur"}
        ]
      }, //添加表单验证规则
      imageUrl: '',
    }
  },
  methods: {
    // 点击查询按钮
    onSubmit() {
      const _this = this;
      getAllUsers({
        username: _this.formInline.username,
        nickname: _this.formInline.nickname,
        email: _this.formInline.email,
        sex: _this.formInline.sex,
        departmentId: _this.formInline.departmentId,
        currentPage: _this.pageInfo.current,
        pageSize: _this.pageInfo.size
      }).then(response => {
        // console.log(response)
        _this.tableData = response.data.data.records;

        _this.pageInfo.total = response.data.data.total;
      }).catch(err => {
        console.log(err)
        console.log("发送错误!")
      })
    },
    // 点击重置按钮
    onRefresh() {
      this.formInline.username = ''
      this.formInline.nickname = ''
      this.formInline.email = ''
      this.formInline.sex = ''
      this.formInline.departmentId = ''
    },
    // 每页显示条数改变事件
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageInfo.size = val;
      this.onSubmit();
    },
    // 显示不同的也是改变事件
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pageInfo.current = val;
      this.onSubmit();
    },
    // 删除数据
    async onDelete(userId) {
      const result = await this.$confirm(`确认删除编号为: ${userId} 的用户吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消退出登入"
        });
      })

      if (result === 'confirm') {
        deleteUser({userId: userId}).then(response => {
          console.log(response)
          if (response.success) {
            this.$message({type: 'success', message: "删除成功!"})
            this.onSubmit();
          } else {
            this.$message({type: 'error', message: "删除失败!"})
          }
        })
      }
    },
    // 加载部门选择框
    async loadDepartmentSelected() {
      await loadDepartment().then(response => {
        // console.log(response)
        this.cities = response.data.data;
      })
    },
    // 关闭添加弹出框
    addClose() {
      if (this.$refs.addFormRef !== undefined) this.$refs.addFormRef.clearValidate();
      this.addForm.birth = "";
      this.addForm = {};
    },
    // 关闭修改弹出框
    updateClose() {
      if (this.$refs.updateFormRef !== undefined) this.$refs.updateFormRef.clearValidate();

      this.updateFrom.birth = "";
      this.updateFrom = {};
    },
    // 添加用户
    async addUser() {
      const _this = this;

      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          _this.btnLoading = true;
          _this.btnDisabled = true;
          addUser(_this.addForm).then(res => {
            if (res.success) {
              _this.$notify.success({
                title: '操作成功',
                message: '用户添加成功',
              });
              _this.addForm = {};
              _this.onSubmit();
            }
          }).catch(err => {
            return _this.$message.error("用户添加失败:" + err.msg);
          })

          _this.addDialogVisible = false;
          _this.btnLoading = false;
          _this.btnDisabled = false;
        } else {
          console.log("表单验证为: " + valid)
        }
      });
    },
    // 显示修改弹出框
    showUpdateDialog(user) {
      this.updateFrom = user;
      this.updateDialogVisible = true;
    },
    // 修改用户
    async updateUser() {
      const _this = this;

      this.$refs.updateFormRef.validate(async valid => {
        if (valid) {
          _this.btnLoading = true;
          _this.btnDisabled = true;
          updateUser(_this.updateFrom).then(res => {
            if (res.success) {
              _this.$notify.success({
                title: '操作成功',
                message: '用户修改成功',
              });
              _this.updateFrom = {};
              _this.onSubmit();
            }
          }).catch(err => {
            return _this.$message.error("用户修改失败:" + err.msg);
          })

          _this.updateDialogVisible = false;
          _this.btnLoading = false;
          _this.btnDisabled = false;
        } else {
          console.log("表单验证为: " + valid)
        }
      });
    },
    // 添加头像成功回调钩子
    handleSuccessFile(response, file, fileList) {
      // console.log(response)

      if (response.success) {
        if (this.updateDialogVisible){

          deleteAvatar({file: this.updateFrom.avatar});
          this.updateFrom.avatar = response.data.url;
        }else {

          deleteAvatar({file: this.addForm.avatar});
          this.addForm.avatar = response.data.url;
        }
      }
    },
    // 添加头像失败回调钩子
    handleErrorFile(err, file, fileList) {
      console.log(err)
      // console.log(file)

      this.$message({type: 'warning', message: '头像添加失败!'})
    },
    // 导出查询条件的数据
    onExportExcel() {

      exportExcel(this.formInline).then(response => {
        console.log(response)
        //这里没有返回数据,但是要在响应头中进行下载操作
        // 将二进制文件转化为可访问的url
        let url = window.URL.createObjectURL(new Blob([response.data]));
        //创建了一个a标签的超链接
        const a = document.createElement("a");
        //将a标签添加到body内容中
        document.body.appendChild(a);
        a.href = url;
        a.download = "用户列表.xls";
        a.click();
        window.URL.revokeObjectURL(url);
      }).catch(error => {
        console.log(error)
      })
    }
  },
  mounted() {
    // 自动调用查询数据
    this.onSubmit();
    // 自动清除查询框
    this.onRefresh();
    // 自动调用加载部门数据
    this.loadDepartmentSelected();
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  line-height: 1.2;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>